<template>
    <div class="ConsumablesStorage">
        <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/ConsumablesStorage' }">易耗品管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/ConsumablesStorage' }"> 易耗品入库</el-breadcrumb-item>
        </el-breadcrumb>
        <h2>入库记录</h2>
        <div class="header">
            <el-row>
                <el-col :span="3">
                    <div @click="dialogFormVisible = true"> <el-button type="primary" icon="el-icon-plus"
                            style="background-color: #3F3F65; ">添加入库记录</el-button>
                    </div>
                </el-col>
                <el-col :span="4">
                    <div class="txtConsumables"><el-input v-model="input" placeholder="请输入名称"
                            style=" width: 150px;"></el-input>
                    </div>
                </el-col>
                <el-col :span="4">
                    <span class="demonstration"> <el-date-picker v-model="value1" type="datetimerange" style="width:200px ;"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker></span>
                </el-col>
                <el-col :span="3">
                    <el-button type="info" style="background-color: #3F3F65;" @click="getdata()"
                        v-model="input">查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-dropdown style="padding-left: 10px;">
                        <el-button type="primary" style="background-color: white; color: #3F3F65; border-color: #3F3F65;">
                            导出Excel<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item></el-dropdown-item>
                            <el-dropdown-item>导出全部</el-dropdown-item><br>
                            <el-dropdown-item>导出选中</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
            </el-row>
        </div>
        <div class="content">
            <el-table :data="tableData" style="width: 100% ;" cell-class-name="table-center"
                @selection-change="SelectTableList">
                <el-table-column type="selection" width="45" header-align="center">
                </el-table-column>
                <el-table-column prop="className" label="分类" width="180" header-align="center">
                </el-table-column>
                <el-table-column prop="cname" label="名称" width="140" header-align="center">
                </el-table-column>
                <el-table-column prop="id" label="编码" width="80" header-align="center">
                </el-table-column>
                <el-table-column prop="cprice" label="单价(元)" width="80" header-align="center">
                </el-table-column>
                <el-table-column prop="cnumber" label="数量" width="80" header-align="center">
                </el-table-column>
                <el-table-column prop="cspecification" label="规格" width="80" header-align="center">
                </el-table-column>
                <el-table-column prop="storageSite" label="存放地点" width="80" header-align="center">
                </el-table-column>
                <el-table-column prop="cdepositTime" label="入库时间" header-align="center">
                </el-table-column>
                <el-table-column prop="address" align="center" label="操作" header-align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button @click="showEditDialog(scope.row.id)" type="primary"
                            style="background-color: #409EFF;border-color:#409EFF" icon="el-icon-edit" circle></el-button>
                        <el-button data-id="row.id" @click="handleDelete(scope.row.id)" type="danger" icon="el-icon-delete"
                            circle></el-button></template>
                </el-table-column>
            </el-table>
            <div class="table-foot"> <el-button type="warning" style="background-color: #3F3F65;"
                    @click="removeHouseByIds">批量删除</el-button>
                <el-pagination background layout="prev, pager, next" :total="total" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-size="pageSize" style="float: right; ">
                </el-pagination>
            </div>
        </div>
        <!-- 添加模态框 -->
        <el-dialog title="新增易耗品" :visible.sync="dialogFormVisible" class="formAdd" @close="addDialogClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-form-item label="选择分类" :label-width="formLabelWidth" prop="classId">
                    <el-select v-model="addForm.classId" placeholder="选择分类" prop="className">
                        <el-option label="实验室器材-玻璃器材" value="1"></el-option>
                        <el-option label="实验室器材-金属器材" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="易耗品名称" :label-width="formLabelWidth" prop="cname">
                    <el-input v-model="addForm.cname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="编码" :label-width="formLabelWidth" prop="id">
                    <el-input v-model="addForm.id" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="单价(元)" :label-width="formLabelWidth" prop="cprice">
                    <el-input v-model="addForm.cprice" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="数量" :label-width="formLabelWidth" prop="cnumber">
                    <el-input v-model="addForm.cnumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="规格" :label-width="formLabelWidth" prop="cspecification">
                    <el-input v-model="addForm.cspecification" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="存放地点" :label-width="formLabelWidth" prop="storageSite">
                    <el-select v-model="addForm.cstorageSiteId" placeholder="存放地点">
                        <el-option label="实验室1" value="1"></el-option>
                        <el-option label="实验室2" value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addwarehousing">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改模态框 -->
        <el-dialog title="修改易耗品" :visible.sync="dialogFormVisibleEdit" class="formEdit">
            <el-form :model="editform" ref="editformRef" :rules="addFormRules">
                <el-form-item label="选择分类" :label-width="formLabelWidth">
                    <el-select v-model="editform.classId" placeholder="选择分类">
                        <el-option label="实验室器材-玻璃器材" value="1"></el-option>
                        <el-option label="实验室器材-金属器材" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="易耗品名称" :label-width="formLabelWidth">
                    <el-input v-model="editform.cname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="编码" :label-width="formLabelWidth">
                    <el-input v-model="editform.id" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="单价" :label-width="formLabelWidth">
                    <el-input v-model="editform.cprice" autocomplete="off">元</el-input>
                </el-form-item>
                <el-form-item label="数量" :label-width="formLabelWidth">
                    <el-input v-model="editform.cnumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="规格" :label-width="formLabelWidth">
                    <el-input v-model="editform.cspecification" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="存放地点" :label-width="formLabelWidth" prop="storageSite">
                    <el-select v-model="editform.cstorageSiteId" placeholder="存放地点">
                        <el-option label="实验室1" value="1"></el-option>
                        <el-option label="实验室2" value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisibleEdit = false">取 消</el-button>
                <el-button type="primary" @click="editwarehousing">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>

import { mapGetters, mapActions } from "vuex";
import axios from "../../utils/axios";
export default {
    data() {
        return {
            currentPage: 1,
            pageSize: 10,
            total: 100,
            value1: '',
            value2: '',
            input: '',
            tableData: [],//存放数据的空数组
            deleteData: [],//复选框数据
            dialogTableVisible: false,
            dialogFormVisible: false,//添加模态框
            dialogFormVisibleEdit: false,//修改模态框

            //添加用户表单数据
            addForm: {
                classId: '',
                cname: '',
                id: '',
                cprice: '',
                cnumber: '',
                cspecification: '',
                cstorageSiteId: '',
                capplyForTime: '',
                storageSite: '',
            },
            //添加表单验证对象
            addFormRules: {
                cname: [
                    { required: true, message: '请输入易耗品名称', trigger: 'blur                                                                                             ' }, {
                        min: 1,
                        message: '输入不能为空',
                        trigger: 'blur'
                    }
                ],
                id: [
                    { required: true, message: '请输入编码', trigger: 'blur' }, {
                        min: 1,
                        message: '输入不能为空',
                        trigger: 'blur'
                    }
                ],
                cprice: [
                    { required: true, message: '请输入单价', trigger: 'blur' }, {
                        min: 1,
                        message: '输入不能为空',
                        trigger: 'blur'
                    }
                ],
                cnumber: [
                    { required: true, message: '请输入数量', trigger: 'blur' }, {
                        min: 1,
                        message: '输入不能为空',
                        trigger: 'blur'
                    }
                ],
                cspecification: [
                    { required: true, message: '请输入规格', trigger: 'blur' }, {
                        min: 1,
                        message: '输入不能为空',
                        trigger: 'blur'
                    }
                ]
            },
            //修改用户表单数据
            editform: {
                capplyForTime: '',
                cname: '',
                id: '',
                cprice: '',
                cnumber: '',
                cspecification: '',
                cstorageSiteId: '',
                classId: '',
                storageSite: '',
            },
            form: {
                classId: '',
                cclassification: '',
                cname: '',
                cnum: '',
                cprice: '',
                creceiveNum: '',
                cspecification: '',
                cstorageSite: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
                id: '',
                cstorageSiteId: '',
            },
            formLabelWidth: '120px',
        }
    },
    methods: {
        ...mapActions(["setTest"]),
        getTest() {
            let res = this.getTest(this.Id);
            if (res.code == 200) {
                this.$message.success('成功！');
            }
        },
        onSubmit() {
            console.log('submit!');
        },
        resetDateFilter() {
            this.$refs.filterTable.clearFilter('date');
        },
        clearFilter() {
            this.$refs.filterTable.clearFilter();
        },
        formatter(row, column) {
            return row.address;
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        filterHandler(value, row, column) {
            const property = column['property'];
            return row[property] === value;
        },
        //显示当前页码
        handleCurrentChange(currentPage) {
            this.currentPage = currentPage;
            console.log('当前页码：', currentPage);
            axios({
                url: 'consumable/warehousing/page',
                method: 'post',
                data: { "page": currentPage, "limit": this.pageSize }
            }).then((r) => {
                this.tableData = r.data.data
            });
        },
        //删除
        handleDelete(id) {

            console.log(id);
            this.$axios.delete(`/consumable/warehousing/delete/${id}`).then((res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    this.$message.success('删除成功！');
                    this.getdata();
                    // this.handleCurrentChange();
                } else { 删除失败 }
            })
        },
        //监听添加数据关闭对话框的事件
        addDialogClose() {
            this.$refs.addFormRef.resetFields();
        },
        //点击确定，添加新数据（预校验）
        addwarehousing() {
            this.$refs.addFormRef.validate(valid => {
                if (!valid) return
                //可以发起添加数据的网络请求
                this.$axios.post('/consumable/warehousing/add', this.addForm).then(() => {
                    this.getdata();
                    this.handleCurrentChange()
                })
                this.$message.success('添加成功!')
                //隐藏添加数据模态框
                this.dialogFormVisible = false

            })
        },
        //展示修改易耗品的模态框
        async showEditDialog(id) {

            const { data: res } = await this.$axios.get('/consumable/warehousing/findById/' + id)
            this.editform = res.data
            this.editform.id = id
            this.dialogFormVisibleEdit = true

        },
        //点击确定，修改数据(预校验)
        async editwarehousing() {
            this.$refs.editformRef.validate(async valid => {
                //发起修改易耗品信息的数据请求
                const date = await this.$axios.put('/consumable/warehousing/update/',
                    {
                        classId: this.editform.classId,
                        cname: this.editform.cname,
                        id: this.editform.id,
                        cprice: this.editform.cprice,
                        cnumber: this.editform.cnumber,
                        cspecification: this.editform.cspecification,
                        cstorageSiteId: this.editform.cstorageSiteId,
                    })
            })
            //关闭模态框
            this.dialogFormVisibleEdit = false
            // this.handleCurrentChange()

            //提示修改成功
            await this.getdata()
            this.$message.success('修改成功！')



        },
        getdata() {
            console.log(this.value1);
            let date1 = ""
            let date2 = ""
            if (this.value1 != "") {
                console.log("in");
                date1 = String(this.msToDate(this.value1[0]));
                date2 = String(this.msToDate(this.value1[1]));
            }

            this.$axios.post('consumable/warehousing/page', { "limit": this.pageSize, "page": this.currentPage, cname: this.input, cdepositTimeBegin: date1, cdepositTimEnd: date2 }
            ).then((r) => {
                this.tableData = r.data.data;
                this.total = r.data.count
            });
        },
        //转时间格式 
        msToDate(msec) {
            let res = this.date(msec)
            let datetime = new Date(res);
            let year = datetime.getFullYear();
            let month = datetime.getMonth();
            let date = datetime.getDate();
            let hour = datetime.getHours();
            let minute = datetime.getMinutes();
            let second = datetime.getSeconds();
            let result1 = year +
                '-' +
                ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
                '-' +
                ((date + 1) < 10 ? '0' + date : date) +
                ' ' +
                ((hour + 1) < 10 ? '0' + hour : hour) +
                ':' +
                ((minute + 1) < 10 ? '0' + minute : minute) +
                ':' +
                ((second + 1) < 10 ? '0' + second : second);

            let result2 = year +
                '-' +
                ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
                '-' +
                ((date + 1) < 10 ? '0' + date : date);
            let result = {
                cdepositTimeBegin: result1,
                cdepositTimEnd: result2
            };

            return result1;

        },

        date(date) {
            let result = new Date(date).getTime();
            return result;
        },
        //批量删除
        SelectTableList(val) {
            this.deleteData = val;
            console.log(val);
        },
        async removeHouseByIds() {
            if (this.deleteData.length == 0) {
                this.$message.error("您还没有勾选易耗品");
                return
            };
            let deletContent = [];
            for (let i = 0; i < this.deleteData.length; i++) {
                let j = this.deleteData[i];
                deletContent.push(j.id)
            }
            console.log(deletContent);
            const confirmResult = await this.$confirm('此操作将删除易耗品，是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).catch(err => {
                return err
            });
            console.log(confirmResult);
            if (confirmResult !== 'confirm') {
                return this.$message.info('取消删除')

            }
            const { data: res } = await this.$axios.delete('/consumable/warehousing/deletes/' + deletContent);
            if (res.code !== 200) {
                return this.$message.error('删除失败！')
            }
            this.$message.success('删除成功！');
            this.getdata();
            // this.handleCurrentChange()
        }

    },
    mounted() {
        // console.log(new Date().Format("yyyy-MM-dd"));
        //刷新数据的方法
        this.getdata()
    },
    computed: {
        tables() { //在你的数据表格中定义tabels
            const input = this.input
            if (input) {
                // console.log("input输入的搜索内容：" + this.input)
                return this.tableData.filter(data => {
                    console.log("object:" + Object.keys(data))
                    return Object.keys(data).some(key => {
                        return String(data[key]).toLowerCase().indexOf(input) > -1
                    })
                })
            }
            return this.tableData
        }
    },
    created() {

    }
};
</script>
<style >
* {
    padding: 0;
    margin: 0;
}



.ConsumablesStorage {
    padding: 29px;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin: 10px 30px;
    padding: 30px;

}

.table-center {
    text-align: center !important;
}

.header {
    text-align: center;
}

.content {
    padding-top: 10px;
}

.el-table {
    border-radius: 10px;
}

.table-foot {
    padding-top: 10px;
}

.formEdit,
.formAdd {
    border-radius: 10px;

}

h2 {
    padding: 10px;
}
</style>
